<template>
	<div class="body">
		<el-form :inline="true" :model="aForm" class="top">
			<el-form-item label="算法名称：">
				<el-input v-model="aForm.algoName" placeholder="算法名称" clearable />
			</el-form-item>
			<el-form-item label="算法类型：">
				<el-select v-model="aForm.langType" clearable placeholder="算法类型">
					<el-option v-for="l in languageList" :key="l" :label="l" :value="l" />
				</el-select>
			</el-form-item>
			<el-form-item label="所属用户：" v-if="isPublic == false">
				<el-input v-model="aForm.userName" placeholder="用户名" clearable />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" :icon="Search" @click="toSearch">查询</el-button>
			</el-form-item>
		</el-form>

		<el-radio-group v-model="isPublic" class="radio" @change="showAlgo">
			<el-radio :value="true" border>公有算法</el-radio>
			<el-radio :value="false" border>私有算法</el-radio>
		</el-radio-group>

		<el-table :data="aList" class="table">
			<el-table-column prop="algoId" label="算法ID" width="100" />
			<el-table-column prop="algoName" label="算法名称" width="180" />
			<el-table-column prop="langType" label="算法类型" width="150" />
			<el-table-column prop="userName" label="所属用户" width="180" v-if="isPublic == false" />
			<el-table-column fixed="right" label="操作">
				<template #default="scope">
					<!-- <el-button type="primary" @click="toUpdate(scope.row)">修改</el-button> -->
					<el-button type="danger" @click="toDelete(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<div class="upload">
			<el-button type="primary" @click="openUpload">上传公有算法</el-button>
		</div>

		<el-dialog
			v-model="toUpload"
			title="上传算法"
			width="600"
			align-center
			:close-on-click-modal="false"
			:show-close="false"
		>
			<el-form :model="aUForm" ref="aUFormRef" :rules="uRules" label-width="auto">
				<el-form-item label="算法名称：" prop="algoName">
					<el-input v-model="aUForm.algoName" placeholder="请输入算法名称"></el-input>
				</el-form-item>
				<el-form-item label="算法类型：" prop="langType">
					<el-radio-group v-model="aUForm.langType" @change="handleLangTypeChange">
						<el-radio label="C">C</el-radio>
						<el-radio label="Java">Java</el-radio>
						<el-radio label="Python">Python</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="选择算法文件：" prop="code">
					<el-upload
						ref="uploadRef"
						:auto-upload="false"
						:on-change="handleFileChange"
						:limit="1"
						:file-list="fileList"
					>
						<template #trigger>
							<el-button type="primary" :disabled="!aUForm.langType">选择文件</el-button>
						</template>
						<template #tip>
							<div class="el-upload__tip">{{ getFileTipText }}</div>
						</template>
					</el-upload>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="canale">取消</el-button>
					<el-button type="primary" @click="submitForm">上传</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- <el-dialog
			v-model="isShow"
			title="算法信息修改"
			width="600"
			align-center
			:close-on-click-modal="false"
			:show-close="false"
		>
			<el-form ref="aFormRef" :model="aUpdateForm" :rules="rules" label-width="auto">
				<el-form-item label="算法ID：" prop="id">
					<el-input v-model="aUpdateForm.id" disabled />
				</el-form-item>
				<el-form-item label="算法名称：" prop="name">
					<el-input v-model="aUpdateForm.name" />
				</el-form-item>
				<el-form-item label="算法类别：" prop="type">
					<el-select v-model="aUpdateForm.type">
						<el-option v-for="l in lOption" :key="l" :label="l" :value="l" />
					</el-select>
				</el-form-item>
				<el-form-item label="是否公有：" prop="isPublic">
					<el-radio-group v-model="aUpdateForm.isPublic">
						<el-radio :label="true">公有</el-radio>
						<el-radio :label="false">私有</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="文件路径：" prop="path">
					<el-input v-model="aUpdateForm.path" disabled />
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="toCanale()">取消</el-button>
					<el-button type="primary" @click="toUpdateSave()">保存</el-button>
				</div>
			</template>
		</el-dialog> -->
	</div>
</template>

<script setup>
	import { reactive, ref, onMounted, computed } from 'vue'
	import { ElMessage, ElMessageBox } from 'element-plus'
	import { algoList, deleteAlgo, saveAlgo } from '@/api/manager'

	const aFormRef = ref(null)

	const rules = {
		id: [{ required: true, trigger: 'blur' }],
		name: [{ required: true, message: '输入算法名称', trigger: 'blur' }],
		type: [
			{
				required: true,
				message: '选择算法类型',
				trigger: 'change'
			}
		],
		isPublic: [
			{
				required: true,
				message: '选择是否公有',
				trigger: 'change'
			}
		],
		path: [{ required: true, trigger: 'blur' }]
	}

	const aForm = reactive({
		algoName: '',
		langType: '',
		userName: ''
	})

	const isPublic = ref(true)

	const aList = ref([])

	const languageList = ref(['C', 'Java', 'Python'])

	// 获取模版数据
	const getAlgoList = async () => {
		let params = {}
		if (isPublic === true) {
			params = {
				isPublic: isPublic.value,
				algoName: aForm.algoName,
				langType: aForm.langType
			}
		} else {
			params = {
				isPublic: isPublic.value,
				algoName: aForm.algoName,
				langType: aForm.langType,
				userName: aForm.userName
			}
		}
		const rData = (await algoList(params)).data
		if (rData.code === 200) {
			aList.value = rData.data
		} else {
			aList.value = []
		}
	}

	onMounted(() => {
		getAlgoList()
	})

	const showAlgo = () => {
		getAlgoList()
	}

	// 查询方法
	const toSearch = () => {
		getAlgoList()
	}

	// 删除算法方法
	const toDelete = (row) => {
		ElMessageBox.confirm('是否删除该算法?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		})
			.then(async () => {
				const data = {
					algoId: row.algoId,
					isPublic: isPublic.value
				}
				const rData = (await deleteAlgo(data)).data
				console.log(rData)

				if (rData.code === '200') {
					ElMessage.success('删除成功')
					getAlgoList()
				} else {
					ElMessage.error('删除失败，' + rData.msg)
				}
			})
			.catch(() => {
				ElMessage.info('取消删除')
			})
	}

	// 算法上传
	const toUpload = ref(false)
	const aUFormRef = ref(null)

	const openUpload = () => {
		toUpload.value = true
	}

	const aUForm = ref({
		algoName: '',
		langType: '',
		code: ''
	})

	const uRules = {
		algoName: [{ required: true, message: '输入算法名', trigger: 'blur' }],
		langType: [{ required: true, message: '选择算法类型', trigger: 'change' }],
		code: [{ required: true, message: '请选择算法文件', trigger: 'change' }]
	}

	const fileList = ref([])
	const uploadRef = ref(null)

	// 根据算法类型获取对应的文件类型
	const acceptType = computed(() => {
		const typeMap = {
			C: '.c',
			Java: '.java',
			Python: '.py'
		}
		return typeMap[aUForm.value.langType] || ''
	})

	// 获取文件提示文本
	const getFileTipText = computed(() => {
		if (!aUForm.value.langType) {
			return '请先选择算法类型'
		}
		return `仅支持上传 ${acceptType.value} 文件，且只能选择一个文件`
	})

	// 处理算法类型变化
	const handleLangTypeChange = () => {
		// 清空已选择的文件
		if (uploadRef.value) {
			uploadRef.value.clearFiles()
		}
		fileList.value = []
		aUForm.value.code = ''
	}

	const handleFileChange = (file) => {
		const fileName = file.name
		const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1)
		const expectedExtension = acceptType.value.replace('.', '')

		if (fileExtension !== expectedExtension) {
			ElMessage.error(`请选择 .${expectedExtension} 文件`)
			// 清空已选择的文件
			if (uploadRef.value) {
				uploadRef.value.clearFiles()
			}
			fileList.value = []
			aUForm.value.code = ''
			return
		}

		const reader = new FileReader()
		reader.onload = (e) => {
			aUForm.value.code = e.target.result
		}
		reader.onerror = () => {
			ElMessage.error('文件读取失败')
		}
		reader.readAsText(file.raw)
	}

	const submitForm = () => {
		aUFormRef.value.validate(async (valid) => {
			if (valid) {
				const rData = (await saveAlgo(aUForm.value)).data
				if (rData.code === 200) {
					ElMessage.success('公有算法上传成功')
					getAlgoList()
					toUpload.value = false
				} else {
					ElMessage.error('算法上传失败，' + rData.msg)
				}
				uploadRef.value.clearFiles()
				aUFormRef.value.resetFields()
			} else {
				return false
			}
		})
	}

	const canale = () => {
		uploadRef.value.clearFiles()
		aUFormRef.value.resetFields()
		ElMessage.info('取消上传算法')
		toUpload.value = false
	}

	// const isShow = ref(false)
	// const aUpdateForm = reactive({
	// 	id: 1,
	// 	name: '',
	// 	type: '',
	// 	isPublic: true,
	// 	path: ''
	// })
	// 打开修改
	// const toUpdate = (row) => {
	// 	aUpdateForm.id = row.id
	// 	aUpdateForm.name = row.name
	// 	aUpdateForm.type = row.type
	// 	aUpdateForm.isPublic = row.isPublic
	// 	aUpdateForm.path = row.path

	// 	isShow.value = true
	// }

	// const toCanale = () => {
	// 	aFormRef.value.resetFields()
	// 	isShow.value = false
	// }

	// const toUpdateSave = () => {
	// 	aFormRef.value.validate((valid) => {
	// 		if (valid) {
	// 			console.log('表单验证通过，提交数据')
	// 			// 这里可以添加调用后端接口提交数据的逻辑
	// 			isShow.value = false
	// 		} else {
	// 			console.log('表单验证失败')
	// 			return false
	// 		}
	// 	})
	// }
</script>

<style lang="scss" scoped>
	.body {
		height: 100%;
		width: 100%;
	}
	.top {
		margin: 5px 0 0 0;
		:deep(.el-form-item__label) {
			font-size: 18px;
			font-weight: bold;
		}
    :deep(.el-form-item){
      margin-right: 10px;
    }
		:deep(.el-form-item__content) {
			width: 130px;
			.el-button {
				width: 100px;
				font-size: 18px;
			}
		}
	}
	.radio {
		margin-bottom: 5px;
	}

	.table {
		height: 65%;
		width: 90%;
	}

	.upload .el-button {
		margin-top: 20px;
		width: 180px;
	}
</style>